package com.yonyougov.devops.cruxcisupport.util;


import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Iputils {

//    public static void main(String[] args) {
//        //    查看端口号是否可用
//        //String ip = "10.16.21.116";
//        String ip = "10.10.66.39";
//        int port = 22;
////        检测Ip是否可用
//        boolean resultIp = Iputils.checkIp(ip,1000);
//        System.out.print("检测的Ip结果为：");
//        System.out.println(resultIp);
////        检测Ip和端口号是否可用
//        boolean resultIpPort = Iputils.checkIpPort(ip, port,1000);
//        System.out.print("检测的Ip和端口结果为：");
//        System.out.println(resultIpPort);
//
//    }

    /**
     * 检测Ip和端口是否可用
     *
     * @param ip
     * @param port
     * @return
     */
    public static boolean checkIpPort(String ip, int port,  Integer timeOut) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(ip,port),timeOut);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {

                }
            }
        }

    }
    /**
     * 检测Ip地址
     *
     * @param ip
     * @return
     */
    public static boolean checkIp(String ip, Integer timeOut){
        try {
            return InetAddress.getByName(ip).isReachable(timeOut);
        } catch (UnknownHostException e) {
            //e.printStackTrace();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return false;
    }

}

